﻿using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using QuickPrompt.BusinessService;
using QuickPrompt.DataAccess;
using QuickPrompt.DomainModel;
using QuickPrompt.DomainModel.Identity;
using QuickPromt.Service;
using RedandBlue.RepositoryPattern.DataContext;
using RedandBlue.RepositoryPattern.EF6;
using RedandBlue.RepositoryPattern.Infrastructure;
using RedandBlue.RepositoryPattern.Repositories;
using RedandBlue.RepositoryPattern.UnitOfWork;

namespace QuickPrompt.Test.IntegrationTests
{
    public class QuickNoteRepositoryTest
    {
        private IQuickNoteService _quickNoteService;
        private IUserService _userService;

        [SetUp]
        public void Initialize()
        {
            var dataContext = new QuickPromptContext();
            _quickNoteService = new QuickNoteService(new Repository<QuickNote>(dataContext, new UnitOfWork(dataContext)));
            _userService = new UserService(new Repository<User>(dataContext, new UnitOfWork(dataContext)));
            //Utility.CreateSeededTestDatabase();
        }

        [TearDown]
        public void Cleanup()
        {
        }

        [Test(Description = "Run Active Prompts")]
        public void RunPrompts()
        {
            _quickNoteService.QueuePrompts();
        }

        [Test(Description = "Get")]
        [TestCase(1)]
        public void Get(int noteId)
        {
            var note = _quickNoteService.GetNote(noteId);
            Assert.IsNotNull(note);
            Assert.IsTrue(note.Name == "Phone Bill");
        }

        [Test(Description = "All Active Notes")]
        public void ActiveNotes()
        {
            var notes = _quickNoteService.Get();
            Assert.IsNotNull(notes);
            Assert.IsTrue(notes.ToList().Any());
        }

        [Test(Description = "All User Active Notes")]
        [TestCase("hbopuri")]
        public void UserNotes(string username)
        {
            var user = _userService.Query(x => x.UserName.Equals(username, StringComparison.OrdinalIgnoreCase))
                  .Select()
                  .FirstOrDefault();
            Assert.IsNotNull(user);

            var notes = _quickNoteService.Get(user.Id);
            Assert.IsNotNull(notes);
            Assert.IsTrue(notes.ToList().Any());
        }

        [Test(Description = "All Prompts that Active and its Notes ")]
        public void ReadyPrompts()
        {
            var notes = _quickNoteService.FetchReadyOnes();
            Assert.IsNotNull(notes);
            var quickNotes = notes as IList<QuickNote> ?? notes.ToList();
            Assert.IsTrue(quickNotes.ToList().Any());
            Assert.IsTrue(quickNotes.All(x=>x.Prompts.Any()));
        }

       

        [Test(Description = "Add a Reminder")]
        [TestCase("hbopuri",
            "Internet & TV Bill", "Check if your payment for monthly Optimum online is posted or not",
              "07/04/2015", "07/04/2016", true, false)]
        [TestCase("hbopuri",
            "Car Payment", "Check car payments",
              "07/04/2015", "07/04/2016", true, false)]
        [TestCase("hbopuri",
            "House Rent", "Check Rent payments",
              "07/04/2015", "07/04/2016", true, false)]
        public void Insert(string username, 
            string name, string description, DateTime startDate, DateTime endDate, bool isActive, bool isDeleted)
        {
            using (IDataContextAsync context = new QuickPromptContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                IRepositoryAsync<User> userRepository = new Repository<User>(context, unitOfWork);
                IRepositoryAsync<QuickNote> quickNoteRepository = new Repository<QuickNote>(context, unitOfWork);
                var user =
                    userRepository.Query(x => x.UserName.Equals(username, StringComparison.OrdinalIgnoreCase))
                        .Select()
                        .FirstOrDefault();
                Assert.IsNotNull(user);

                var quickNote = new QuickNote
                {
                    Name = name,
                    Description = description,
                    StartDateUtc = startDate.ToUniversalTime(),
                    EndDateUtc = endDate.ToUniversalTime(),
                    IsActive = isActive,
                    IsDeleted = isDeleted,
                    DateCreatedUtc = DateTime.UtcNow,
                    LastUpdatedUtc = DateTime.UtcNow,
                    UserGuid = user.Id,
                    UpdatedByUserId = 0,
                    LastActivityIpAddress = null,
                    ObjectState = ObjectState.Added
                };

                quickNote.Prompts.Add(new Prompt
                {
                    //NoteId = quickNote.Id,
                    DateCreatedUtc = DateTime.UtcNow,
                    PromptType = PromptType.Text,
                    AddressValue = "5167493582",
                    IsActive = isActive,
                    IsDeleted = isDeleted,
                    LastActivityIpAddress = null,
                    LastUpdatedUtc = DateTime.UtcNow,
                    StartingFromUtc = DateTime.UtcNow,
                    ObjectState = ObjectState.Added,
                    PromptFrequency = PromptFrequency.Daily,
                    PromptTimeZone = "EST",
                });

                unitOfWork.Repository<QuickNote>().Insert(quickNote);
                unitOfWork.Repository<Prompt>().InsertRange(quickNote.Prompts);
                context.SaveChanges();
                //quickNoteRepository.Insert(quickNote);
                //try
                //{
                //    unitOfWork.Repository<QuickNote>().Insert(quickNote);
                //    //quickNoteRepository.Insert(quickNote);
                //    unitOfWork.SaveChanges();
                //}
                //catch (DbEntityValidationException ex)
                //{
                //    Debug.WriteLine(ex.GetEntityValidationException());
                //}
                //catch (Exception ex)
                //{
                //    Debug.WriteLine(ex.Message);
                //}
                var insertedNote = quickNoteRepository.Query(x => x.Name == name).Include(x=>x.Prompts).Select().FirstOrDefault();
                Assert.IsNotNull(insertedNote);
                Assert.IsTrue(insertedNote.Prompts.Any());
                Assert.IsTrue(insertedNote.Name == name);
            }
        }
    }
}
